<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input style="width: 240px; margin-right: 10px" v-model="data.name" placeholder="请输入名称" />
      <el-button type="primary" @click="load">查询</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="delBatch">批量删除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="名称" prop="name" />
        <el-table-column label="操作" width="300px">
          <template #default="scope">
            <div style="display: flex; gap: 4px; align-items: center;padding-right: 200px">
              <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit"></el-button>
              <el-button @click="del(scope.row.id)" type="danger" :icon="Delete"></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 15px">
      <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
      />
    </div>
    <el-dialog title="部门信息" v-model="data.formVisible" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { Edit, Delete, Search } from '@element-plus/icons-vue';
import request from '@/utils/request.js';
import { ElMessage, ElMessageBox } from 'element-plus';

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: [],
  rules: {
    name: [
      { required: true, message: '请输入名称', trigger: 'blur' }
    ]
  }
});

const formRef = ref();

const load = () => {
  request.get('/department/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    data.tableData = res.data.list;
    data.total = res.data.total;
  });
};
load();


const handleAdd = () => {
  data.formVisible = true;
  data.form = {};
};

const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      data.form.id? updateById() : add();
    }
  });
};

const add = () => {
  request.post('/department/add', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false;
      ElMessage.success('操作成功');
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.formVisible = true;
};

const updateById = () => {
  request.put('/department/updateById', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false;
      ElMessage.success('操作成功');
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const del = (id) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' })
      .then(() => {
        request.delete(`/department/deleteById/${id}`).then(res => {
          if (res.code === '200') {
            ElMessage.success('操作成功');
            load();
          } else {
            ElMessage.error(res.msg);
          }
        });
      })
      .catch(() => {});
};

const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id);
  console.log(data.ids);
};

const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据');
    return;
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' })
      .then(() => {
        request.delete('/department/deleteBatch', { data: data.ids }).then(res => {
          if (res.code === '200') {
            ElMessage.success('操作成功');
            load();
          } else {
            ElMessage.error(res.msg);
          }
        });
      })
      .catch(() => {});
};
</script>